package com.joker.demo.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.joker.demo.admin.domain.po.EnvironmentMonitorPO;
import com.joker.demo.admin.domain.vo.EnvironmentMonitorStatisticsVO;
import com.joker.demo.admin.mapper.EnvironmentMonitorMapper;
import com.joker.demo.admin.service.EnvironmentMonitorService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDateTime;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 环境监控服务实现类
 *
 * @author : feixiang.li
 * @since : 2025-01-27 10:30
 */
@Slf4j
@Service
public class EnvironmentMonitorServiceImpl implements EnvironmentMonitorService {

    @Resource
    private EnvironmentMonitorMapper environmentMonitorMapper;

    @Override
    public void saveMonitorData(EnvironmentMonitorPO monitorPO) {
        try {
            if (monitorPO == null) {
                log.warn("环境监控数据为空，跳过保存");
                return;
            }

            // 设置创建时间和更新时间
            LocalDateTime now = LocalDateTime.now();
            monitorPO.setCreateTime(now);
            monitorPO.setUpdateTime(now);

            // 保存到数据库
            environmentMonitorMapper.insert(monitorPO);
            
            log.debug("环境监控数据保存成功，执行器：{}，时间：{}", 
                    monitorPO.getRegisterKey(), monitorPO.getMonitorTime());
                    
        } catch (Exception e) {
            log.error("保存环境监控数据失败，执行器：{}，错误：{}", 
                    monitorPO != null ? monitorPO.getRegisterKey() : "null", e.getMessage(), e);
        }
    }

    @Override
    public void cleanHistoryData(Integer days) {
        try {
            if (days == null || days <= 0) {
                log.warn("清理历史数据参数无效，days：{}", days);
                return;
            }

            // 计算清理时间点
            LocalDateTime cleanTime = LocalDateTime.now().minusDays(days);
            
            // 构建删除条件
            LambdaQueryWrapper<EnvironmentMonitorPO> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.lt(EnvironmentMonitorPO::getMonitorTime, cleanTime);
            
            // 执行删除
            int deletedCount = environmentMonitorMapper.delete(queryWrapper);
            
            log.info("环境监控历史数据清理完成，清理 {} 天前的数据，删除记录数：{}", days, deletedCount);
            
        } catch (Exception e) {
            log.error("清理环境监控历史数据失败，错误：{}", e.getMessage(), e);
        }
    }

    @Override
    public IPage<EnvironmentMonitorPO> page(Page<EnvironmentMonitorPO> page, Wrapper<EnvironmentMonitorPO> queryWrapper) {
        try {
            return environmentMonitorMapper.selectPage(page, queryWrapper);
        } catch (Exception e) {
            log.error("分页查询环境监控数据失败", e);
            throw new RuntimeException("分页查询环境监控数据失败", e);
        }
    }

    @Override
    public List<EnvironmentMonitorPO> queryLatestMonitorData() {
        try {
            // 查询每个执行器的最新监控数据
            List<EnvironmentMonitorPO> allData = environmentMonitorMapper.selectList(null);
            
            // 按执行器分组，获取每个执行器的最新数据
            return allData.stream()
                    .collect(Collectors.groupingBy(EnvironmentMonitorPO::getRegisterKey))
                    .values()
                    .stream()
                    .map(executorData -> executorData.stream()
                            .max((a, b) -> a.getMonitorTime().compareTo(b.getMonitorTime()))
                            .orElse(null))
                    .filter(data -> data != null)
                    .collect(Collectors.toList());
        } catch (Exception e) {
            log.error("查询最新环境监控数据失败", e);
            throw new RuntimeException("查询最新环境监控数据失败", e);
        }
    }

    @Override
    public List<EnvironmentMonitorPO> query24HourSummaryData() {
        try {
            // 计算24小时前的时间
            LocalDateTime startTime = LocalDateTime.now().minusHours(24);
            return environmentMonitorMapper.query24HourSummaryData(startTime);
        } catch (Exception e) {
            log.error("查询24小时汇总环境监控数据失败", e);
            return Collections.emptyList();
        }
    }

    @Override
    public EnvironmentMonitorPO query24HourSummaryDataByRegisterKey(String registerKey) {
        try {
            if (!StringUtils.hasText(registerKey)) {
                log.warn("执行器标识为空");
                return null;
            }
            // 计算24小时前的时间
            LocalDateTime startTime = LocalDateTime.now().minusHours(24);
            return environmentMonitorMapper.query24HourSummaryDataByRegisterKey(registerKey, startTime);
        } catch (Exception e) {
            log.error("查询执行器24小时汇总环境监控数据失败，registerKey：{}", registerKey, e);
            return null;
        }
    }

    @Override
    public EnvironmentMonitorPO queryLatestMonitorDataByRegisterKey(String registerKey) {
        try {
            if (!StringUtils.hasText(registerKey)) {
                log.warn("执行器标识为空");
                return null;
            }

            LambdaQueryWrapper<EnvironmentMonitorPO> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(EnvironmentMonitorPO::getRegisterKey, registerKey);
            queryWrapper.orderByDesc(EnvironmentMonitorPO::getMonitorTime);
            queryWrapper.last("limit 1");

            return environmentMonitorMapper.selectOne(queryWrapper);
        } catch (Exception e) {
            log.error("查询执行器最新环境监控数据失败，registerKey：{}", registerKey, e);
            throw new RuntimeException("查询执行器最新环境监控数据失败", e);
        }
    }

    @Override
    public List<EnvironmentMonitorPO> queryMonitorDataHistory(String registerKey, Date startTime, Date endTime, Integer limit) {
        try {
            if (!StringUtils.hasText(registerKey)) {
                log.warn("执行器标识为空");
                return new java.util.ArrayList<>();
            }

            LambdaQueryWrapper<EnvironmentMonitorPO> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(EnvironmentMonitorPO::getRegisterKey, registerKey);
            
            if (startTime != null) {
                queryWrapper.ge(EnvironmentMonitorPO::getMonitorTime, startTime);
            }
            if (endTime != null) {
                queryWrapper.le(EnvironmentMonitorPO::getMonitorTime, endTime);
            }
            
            queryWrapper.orderByDesc(EnvironmentMonitorPO::getMonitorTime);
            
            if (limit != null && limit > 0) {
                queryWrapper.last("limit " + limit);
            }

            return environmentMonitorMapper.selectList(queryWrapper);
        } catch (Exception e) {
            log.error("查询执行器环境监控历史数据失败，registerKey：{}", registerKey, e);
            throw new RuntimeException("查询执行器环境监控历史数据失败", e);
        }
    }

    @Override
    public EnvironmentMonitorStatisticsVO queryMonitorStatistics(LocalDateTime startTime, LocalDateTime endTime) {
        try {
            EnvironmentMonitorStatisticsVO statistics = new EnvironmentMonitorStatisticsVO();
            
            // 构建查询条件
            LambdaQueryWrapper<EnvironmentMonitorPO> queryWrapper = new LambdaQueryWrapper<>();
            if (startTime != null) {
                queryWrapper.ge(EnvironmentMonitorPO::getMonitorTime, startTime);
            }
            if (endTime != null) {
                queryWrapper.le(EnvironmentMonitorPO::getMonitorTime, endTime);
            }
            
            List<EnvironmentMonitorPO> dataList = environmentMonitorMapper.selectList(queryWrapper);
            
            if (dataList.isEmpty()) {
                // 如果没有数据，返回默认值
                statistics.setTotalExecutors(0);
                statistics.setAverageCpuUsage(BigDecimal.ZERO);
                statistics.setAverageSystemMemoryUsage(BigDecimal.ZERO);
                statistics.setAverageHeapMemoryUsage(BigDecimal.ZERO);
                return statistics;
            }
            
            // 计算统计数据
            int totalExecutors = (int) dataList.stream()
                    .map(EnvironmentMonitorPO::getRegisterKey)
                    .distinct()
                    .count();
            
            // 计算平均CPU使用率
            BigDecimal avgCpuUsage = dataList.stream()
                    .filter(data -> data.getCpuUsagePercent() != null)
                    .map(EnvironmentMonitorPO::getCpuUsagePercent)
                    .reduce(BigDecimal.ZERO, BigDecimal::add)
                    .divide(BigDecimal.valueOf(dataList.stream()
                            .filter(data -> data.getCpuUsagePercent() != null)
                            .count()), 2, RoundingMode.HALF_UP);
            
            // 计算平均内存使用率
            BigDecimal avgMemoryUsage = dataList.stream()
                    .filter(data -> data.getSystemMemoryUsagePercent() != null)
                    .map(EnvironmentMonitorPO::getSystemMemoryUsagePercent)
                    .reduce(BigDecimal.ZERO, BigDecimal::add)
                    .divide(BigDecimal.valueOf(dataList.stream()
                            .filter(data -> data.getSystemMemoryUsagePercent() != null)
                            .count()), 2, RoundingMode.HALF_UP);
            
            // 计算平均堆内存使用率
            BigDecimal avgHeapMemoryUsage = dataList.stream()
                    .filter(data -> data.getHeapMemoryUsagePercent() != null)
                    .map(EnvironmentMonitorPO::getHeapMemoryUsagePercent)
                    .reduce(BigDecimal.ZERO, BigDecimal::add)
                    .divide(BigDecimal.valueOf(dataList.stream()
                            .filter(data -> data.getHeapMemoryUsagePercent() != null)
                            .count()), 2, RoundingMode.HALF_UP);
            
            statistics.setTotalExecutors(totalExecutors);
            statistics.setAverageCpuUsage(avgCpuUsage);
            statistics.setAverageSystemMemoryUsage(avgMemoryUsage);
            statistics.setAverageHeapMemoryUsage(avgHeapMemoryUsage);
            
            return statistics;
        } catch (Exception e) {
            log.error("查询环境监控统计信息失败", e);
            throw new RuntimeException("查询环境监控统计信息失败", e);
        }
    }

    @Override
    public List<String> queryAllExecutors() {
        try {
            List<EnvironmentMonitorPO> allData = environmentMonitorMapper.selectList(null);
            return allData.stream()
                    .map(EnvironmentMonitorPO::getRegisterKey)
                    .distinct()
                    .collect(Collectors.toList());
        } catch (Exception e) {
            log.error("查询所有执行器列表失败", e);
            throw new RuntimeException("查询所有执行器列表失败", e);
        }
    }
}
